<?php
declare (strict_types = 1);

namespace app\controller;

// 引入校验
use app\validate\Member as MemberValidate;
use think\exception\ValidateException;

// 引入缓存
use think\facade\Cache;

use think\Request;
use tinywan\JWT;

// model类
use app\model\Member as MemberModel;
// 权限model类
use app\model\Auth as AuthModel;

use app\service\Menu as MenuService;

class Member extends Base
{
    /**
     * 查询账户列表
     *
     * @param  \think\Request  $request
     * @return json
     */
    public function index(Request $request)
    {
        $params = request()->rsa_data;
        // 获取数据区域
        $name = $params['name'] ? $params['name'] : '';
        $page = $params['page'] ? intval($params['page']) : 1;
        $size = $params['size'] ? intval($params['size']) : 10;
        
        $where = [];
        if (!empty($name)) {
            $where[] = ['username', 'like', "{$name}%"];
            $where[] = ['mobile', 'like', "{$name}%"];
        }
        $field_name = 'id,is_check,gender,username,nickname,mobile,group_id,last_login_ip,last_login_time';
        $list = MemberModel::field($field_name)->whereOr($where)->page($page,$size);
        $auth = AuthModel::field('id,permission_name as name')->select()->toArray();
        $data = [
            // 总条数
            'total' => $list->count(),
            // 查询指定数据
            'list'  => $list->select()->toArray(),
            // 页码
            'page'  => $page,
            'auth' => $auth,
        ];
        return $this->createMsg($data, '查询成功!', 200);
    }
    
    /**
     * 创建账户
     *
     * @param  \think\Request  $request
     * @return json
     */
    public function add(Request $request)
    {
        $params = request()->rsa_data;
        try {
            // 校验是否符合新增规则
            validate(MemberValidate::class)->scene('add')->check($params);
            
            // 判断账户是否存在
            $user = MemberModel::where('username', $params['username'])->findOrEmpty();
            if ($user->isEmpty()) {
                // 账户不存在可以添加
                // 随机盐值
                $salt = random_string(8);
                $newUser = MemberModel::create([
                    // 用户名
                    'username'  =>  $params['username'],
                    // md5盐加密后的密码
                    'password'  =>  md5_password($params['password'],$salt),
                    // 盐值
                    'salt'      =>  $salt,
                    // 昵称
                    'nickname'  =>  $params['username'],
                    // 是否禁用 0 默认禁用
                    'is_check'  =>  $params['is_check'] ? $params['is_check'] : 0,
                ]);
                return $this->createMsg([], '添加账户成功!', 200);
            }else{
                return $this->createMsg([], '该账户已经存在!', 400);
            }
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->createMsg([], $e->getError(), 400);
        }
    }
    
    
    
    /**
     * 改变账户状态
     *
     * @param  \think\Request  $request
     * @return json
     */
    public function change(Request $request)
    {
        $params = request()->rsa_data;
        if (!empty($params['id']) && (intval($params['is_check']) === 1 || intval($params['is_check'])  === 0)) {
            // 判断账户是否存在
            $user = MemberModel::whereFindInSet('id', $params['id'])->find();
            if ($user['group_id'] === 1) {
               return $this->createMsg([], '管理员禁止修改!', 400);
            }
            if ($user) {
                $user->is_check = $params['is_check'];
                $user->save();
                return $this->createMsg([], '修改状态完成!', 200);
            }else{
                return $this->createMsg([], '未查找到该用户!', 400);
            }
        }else{
            return $this->createMsg([], '数据不足', 400);
        }
    }
    
    /**
     * 编辑用户
     *
     * @param  \think\Request  $request
     * @return json
     */
    public function edit(Request $request)
    {
        $params = request()->rsa_data;
        try{
            validate(MemberValidate::class)->scene('edit')->check($params);
            // 判断账户是否存在
            $user = MemberModel::whereFindInSet('id', $params['id'])->find();
            if ($user) {
                // 管理员禁止修改
                if ($user['group_id'] === 1) {
                   return $this->createMsg([], '管理员禁止修改!', 400);
                }
                // 编辑用户用户
                if(!empty($params['is_check'])) $user->is_check = $params['is_check'];
                if(!empty($params['username'])) $user->username = $params['username'];
                if(!empty($params['group_id'])) $user->group_id = $params['group_id'];
                if(!empty($params['gender']) || $params['gender'] === 0) $user->gender = $params['gender'];
                if(!empty($params['nickname'])) $user->nickname = $params['nickname'];
                if(!empty($params['mobile'])) $user->mobile = $params['mobile'];
                
                // 如果有填写密码就重新加密修改
                if(!empty($params['password'])) $user->password = md5_password($params['password'],$user->salt);
                if($user->save()){
                    return $this->createMsg([], '编辑用户完成!', 200);
                }else{ 
                    return $this->createMsg([], '编辑用户失败!', 400);
                }
                
                
            }else{
                return $this->createMsg([], '未查找到该用户!', 400);
            }
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->createMsg([], $e->getError(), 400);
        }
    }
    
    /**
     * 删除用户
     *
     * @param  \think\Request  $request
     * @return json
     */
    public function delete(Request $request)
    {
        $params = request()->rsa_data;
        try {
            validate(MemberValidate::class)->scene('delete')->check($params);
            
            // 判断账户是否存在
            $user = MemberModel::whereFindInSet('id', $params['id'])->find();
            if ($user) {
                // 管理员禁止修改
                if ($user['group_id'] === 1) {
                   return $this->createMsg([], '管理员禁止修改!', 400);
                }
                // 删除用户
                MemberModel::where('id',$params['id'])->delete();
                return $this->createMsg([], '删除用户完成!', 200);
            }else{
                return $this->createMsg([], '未查找到该用户!', 400);
            }
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $this->createMsg([], $e->getError(), 400);
        }
    }
    
    /**
     * 获取用户权限值
     *
     * @param  \think\Request  $request
     * @return json
     */
    public function permission(Request $request)
    {
        $permission = [];
        $uid = JWT::getExtendVal('id');
        $group_id = MemberModel::where('id',$uid)->value('group_id');
        if(!empty($group_id)){
            // 获取全部导航与接口目录
            $MenuService = new MenuService();
            $list = $MenuService->getMenuList();
            if($group_id === 1){
                foreach ($list as $menu) {
                    array_push($permission,$menu['permission_value']);
                    if(!empty($menu['children'])){
                        foreach ($menu['children'] as $control){
                            array_push($permission,$menu['permission_value'].'.'.$control['permission_value']);
                            if (!empty($control['children'])) {
                                foreach ($control['children'] as $value){
                                    array_push($permission,$menu['permission_value'].'.'.$control['permission_value'].'.'.$value['permission_value']);
                                }
                            }
                        }
                    }
                }
            }else{
                $ids_data = AuthModel::where('id',$group_id)->value('permission_ids');
                if(!$ids_data) return $this->createMsg([],'请寻找管理员授权!',400);
                // 权限值字符串转化为数组
                $ids = explode(',', $ids_data);
                foreach ($list as $menu) {
                    if (in_array($menu['id'], $ids)) {
                        array_push($permission,$menu['permission_value']);
                    }
                    if(!empty($menu['children'])){
                        foreach ($menu['children'] as $control){
                            if (in_array($control['id'], $ids)) {
                                array_push($permission,$menu['permission_value']);
                                array_push($permission,$menu['permission_value'].'.'.$control['permission_value']);
                            }
                            if (!empty($control['children'])) {
                                foreach ($control['children'] as $value){
                                    if (in_array($value['id'], $ids)) {
                                        array_push($permission,$menu['permission_value']);
                                        array_push($permission,$menu['permission_value'].'.'.$control['permission_value']);
                                        array_push($permission,$menu['permission_value'].'.'.$control['permission_value'].'.'.$value['permission_value']);
                                    }
                                }
                            }
                        }
                    }
                }
                // 数组去重
                $permission = array_values(array_unique($permission));
            }
        }
        return $this->createMsg($permission, '查询成功!', 200);
    }
}
